package com.ayh.campusfun.controller.api.v1;

import com.alibaba.fastjson.JSON;
import com.ayh.campusfun.common.CommonResult;
import com.ayh.campusfun.common.core.jwt.JWTUtils;
import com.ayh.campusfun.common.exception.http.ForbiddenException;
import com.ayh.campusfun.common.utils.PraMap;
import com.ayh.campusfun.controller.api.v1.websocket.MyWebSocket;
import com.ayh.campusfun.entity.GoodFriend;
import com.ayh.campusfun.entity.Message;
import com.ayh.campusfun.entity.Users;
import com.ayh.campusfun.service.GoodFriendService;
import com.ayh.campusfun.service.MessageService;
import com.ayh.campusfun.service.UsersService;
import com.ayh.campusfun.vo.FriendVO;
import com.ayh.campusfun.vo.UsersVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 好友表(GoodFriend)表控制层
 *
 * @author ayh
 * @since 2021-03-20 20:42:38
 */
@RestController
@RequestMapping("goodFriend")
public class GoodFriendController {
    /**
     * 服务对象
     */
    @Autowired
    private GoodFriendService goodFriendService;

    @Autowired
    private UsersService usersService;

    @Resource
    private JWTUtils jwtUtils;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    MessageService messageService;


    @PostMapping(value = "/updateFriend",produces = "application/json")
    public CommonResult updateOrInsertFriend(HttpServletRequest request, GoodFriend goodFriend,Integer type){
        String authorization =  jwtUtils.getTokenFromRequest(request);
        Users users = (Users) redisTemplate.opsForValue().get(authorization);
        if(users==null){
            throw new ForbiddenException(60009);
        }
        String uid = users.getUid();
        goodFriend.setUid(uid);
        if(type==1) {
            goodFriendService.updateById(goodFriend);
        }else if(type==2){
            goodFriendService.insert(goodFriend);
        }
        return CommonResult.successNoData();
    }

    @PostMapping(value = "/findFriend",produces = "application/json")
    public CommonResult findFriend(HttpServletRequest request, String keyWord,Integer type){
        String authorization =  jwtUtils.getTokenFromRequest(request);
        Users users = (Users) redisTemplate.opsForValue().get(authorization);
        if(users==null){
            throw new ForbiddenException(60009);
        }
        String uid = users.getUid();
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("uid",uid);
        map.put("keyWord",keyWord);
        if(type==1) {
            return CommonResult.success(
                    goodFriendService.searchFriendList(map)
            );
        }else if(type==2){
            return CommonResult.success(
                    UsersVO.buildList( usersService.queryUserByParam(map))
            );
        }
        return CommonResult.successNoData();
    }

    @PostMapping("/findFriendList")
    public CommonResult getFriendList(HttpServletRequest request,Integer friendStatus){
        String uid = jwtUtils.getUidFromRequest(request);
        List<FriendVO> friendList;
        if(friendStatus == 2){
            friendList = goodFriendService.findFriendList(PraMap.create().put("friendId", uid).put("friendStatus", 2));
        }else{
            friendList = goodFriendService.findFriendList(PraMap.create().put("uid", uid).put("friendStatus", 1));
        }
        return CommonResult.success(friendList);
    }
    
    @PostMapping("/addFriend")
    public CommonResult addFriend(HttpServletRequest request,
                                  String friendId, String friendNickname,
                                  String friendName, String authMessage) throws IOException {
        String uid = jwtUtils.getUidFromRequest(request);
        String userName = jwtUtils.getUserName(jwtUtils.getTokenFromRequest(request));
        Long id = goodFriendService.findFriendByUidAndFriendId(uid, friendId);
        if(null != id && id != 0){
            goodFriendService.deleteById(id);
        }
        GoodFriend goodFriend = GoodFriend.builder()
                .friendId(friendId)
                .uid(uid)
                .friendNickname(friendNickname)
                .friendName(friendName)
                .authMsg(authMessage)
                .msgStatus(2)
                .friendStatus(2).build();
        Long insert = goodFriendService.insert(goodFriend);
        Message addFriendMsg = Message.builder()
                .avatar("https://campus-fun.oss-cn-beijing.aliyuncs.com/avatar/512x512.png")
                .friendName("新朋友")
                .contentText(userName + "请求添加你为好友")
                .contentType(-1)
                .toFriendId(friendId)
                .messageStatus(-1)
                .sendTime(new Date())
                .uid("-1")
                .build();
        if(MyWebSocket.webSocketMap.get(friendId) != null){
            MyWebSocket.webSocketMap.get(friendId).sendMessage(JSON.toJSONString(addFriendMsg));
        }
        return CommonResult.success(insert);
    }

    @PostMapping("/findFriendByUid")
    public CommonResult findFriendBuUid(HttpServletRequest request ,String friendId){
        String uid = jwtUtils.getUidFromRequest(request);
        FriendVO friendVO =  goodFriendService.findFriendByUid(uid,friendId);
        return CommonResult.success(friendVO);
    }

    @PostMapping("/findGoodFriendAuthMsgList")
    public CommonResult findGoodFriendAuthMsgList(HttpServletRequest request){
        String uid = jwtUtils.getUidFromRequest(request);
        Map<String,Object> map = new HashMap<>();
        map.put("uid", uid);
        map.put("order", "add_time desc");
        List<GoodFriend> list = goodFriendService.findGoodFriendAuthMsgList(map);
        return CommonResult.success(list);
    }
    
    @PostMapping("/agreeAddFriend")
    public CommonResult agreeAddFriend(HttpServletRequest request, String friendUid, Long id, String friendName, String friendNickname) throws IOException {
        String uid = jwtUtils.getUidFromRequest(request);
        GoodFriend goodFriend = GoodFriend.builder()
                .id(id)
                .friendStatus(1)
                .build();
        goodFriendService.updateById(goodFriend);
        Long friendId = goodFriendService.findFriendByUidAndFriendId(uid, friendUid);
        if(null != friendId && friendId != 0){
            goodFriend.setId(friendId);
            goodFriendService.updateById(goodFriend);
        }
        else {
            GoodFriend friend = GoodFriend.builder()
                    .friendId(friendUid)
                    .uid(uid)
                    .friendStatus(1)
                    .friendName(friendName)
                    .friendNickname(friendNickname)
                    .build();
            goodFriendService.insert(friend);
        }
        FriendVO friendByUid = goodFriendService.findFriendByUid(friendUid,uid);
        FriendVO friendByUid1 = goodFriendService.findFriendByUid(uid, friendUid);
//        给好友发送消息(我发给好友)
        Message addFriendMsg = Message.builder()
                .avatar(jwtUtils.getUserAvatar(jwtUtils.getTokenFromRequest(request)))
                .toFriendId(friendUid)
                .uid(uid)
                .contentType(1)
                .contentText("我们已经是好友了，可以聊天啦！")
                .friendName(friendByUid.getFriendName())
                .build();
        Long insert = messageService.insert(addFriendMsg);
        Message byId = messageService.findById(addFriendMsg.getId());
        byId.setFriendName(friendByUid.getFriendName());
        if(MyWebSocket.webSocketMap.get(byId.getToFriendId()) != null ){
            MyWebSocket.webSocketMap.get(byId.getToFriendId()).sendMessage(JSON.toJSONString(byId));
        }
//        发送给自己消息（模拟好友发给我）
        Message message = Message.builder()
                .avatar(friendByUid1.getAvatarUrl())
                .toFriendId(uid)
                .uid(friendUid)
                .contentType(1)
                .contentText("我们已经是好友了，可以聊天啦！")
                .friendName(friendByUid1.getFriendName())
                .build();
        Long insert1 = messageService.insert(message);
        Message byId1 = messageService.findById(message.getId());
        byId1.setFriendName(friendByUid1.getFriendName());
        if(MyWebSocket.webSocketMap.get(byId1.getToFriendId()) != null){
            MyWebSocket.webSocketMap.get(byId1.getToFriendId()).sendMessage(JSON.toJSONString(byId1));
        }
        return CommonResult.success("添加成功");
    }
    
    @PostMapping("/updateGoodFriendMsgStatus")
    public CommonResult updateGoodFriendMsgStatus(HttpServletRequest request){
        String uid = jwtUtils.getUidFromRequest(request);
        goodFriendService.updateMsgStatusByUid(uid);
        return CommonResult.success("修改成功");
    }

    @PostMapping("/refuseAddFriend")
    public CommonResult refuseAddFriend(Long id){
        GoodFriend goodFriend = GoodFriend.builder()
                .id(id)
                .friendStatus(3)
                .build();
        goodFriendService.updateById(goodFriend);
        return CommonResult.success("拒绝成功");
    }

}
